<?php
class CommentController extends Controller
{
	public function actionLike()
	{ 
		$transaction = Yii::app()->db->beginTransaction();
		try {
			if(isset($_GET['comment_id'], $_GET['like_action'], $_GET['uid'])) {
				$comment = Comment::model()->findByPk($_GET['comment_id']);
				if($comment == null) {
					throw new PlatwoException(9999, 'Comment not found.');
				}
				$likeGroup = LikeGroup::model()->findByPk($comment->like);
				if($likeGroup == null) {
					$likeGroup = new LikeGroup();
					$likeGroup->save();
				}
				$comment->like = $likeGroup->like_group_id;
				if(!$comment->save()) {
					throw new PlatwoException(9999, 'comment');
				}
				$like = Like::model()->findByAttributes(array('like_group'=> $comment->like, 'uid'=> $_GET['uid']));
				if($_GET['like_action'] === "true" || $_GET['like_action'] === true) {
					$like = new Like();
					$like->uid = $_GET['uid'];
					$like->like_group = $comment->like;
					if(!$like->save()) {
						throw new PlatwoException(9999, 'Can not add like.');
					}
				}
				else {
					if($like != null) {
						if(!$like->delete()) {
							throw new PlatwoException(9999, 'Can not delete like.');
						}
					}
				}
				$count = Like::model()->count("like_group=:like_group", array('like_group'=> $comment->like));
				$likeGroup->like_count = $count;
				if(!$likeGroup->save()) {
					throw new PlatwoException(9999, 'Can not update like count.');
				}
				$resp = $comment->getAttributes();
				$liked = Like::model()->count("like_group=:like_group AND uid=:uid", array(':like_group'=> $comment->like, ':uid'=> $_GET['uid'])) == 0 ? false: true;
				$resp['liked'] = $liked;
				$resp['likes'] = $likeGroup->like_count;
				$transaction->commit();
				
				echo CJSON::encode($resp);
			}
		} catch(PlatwoException $e) {
			$transaction->rollback();
			echo $e->toJSON();
		}
	}
	
	public function actionFetch()
	{
		try {
			if(!isset($_GET['photo_id'], $_GET['offset'], $_GET['length'])) {
				throw new PlatwoException(9999, 'Need parameters photo_id, offset, length');
			}
			$photo = Photo::model()->findByPk($_GET['photo_id']);
			if($photo == null) {
				throw new PlatwoException(9999, 'Photo not found.');
			}
			$comments = Comment::model()->findAllByAttributes(array('comment_group'=> $photo->comment_group), array(
					'order'=> 'comment_time DESC',
					'offset'=> $_GET['offset'],
					'limit'=> $_GET['length'],
					));
			$resp = array();
			foreach($comments as $key => $comment) {
				$resp[$key] = $comment->getAttributes();
				$account = Account::model()->findByPk($comment->uid);
				$resp[$key]['from'] = $account->getAttributes(array('id', 'name'));
			}
			echo CJSON::encode($resp);
		} catch(PlatwoException $e) {
			echo $e->toJSON();
		}
	}
}